package com.yd.app.service.pc.jewellery.jewelleryPageService;

import com.yd.app.mapper.OrderMapper;
import com.yd.app.service.common.BaseService;
import com.yd.app.service.mobile.messageService.MMessageService;
import com.yd.app.service.pc.permissionService.PermissionService;
import com.yd.app.service.pc.userCartService.UserCartService;
import com.yd.app.service.ruanwei.interfacej.SmsClientSend;
import com.yd.app.util.BusinessException;
import com.yd.app.util.SmsModelUtil;
import com.yd.domain.business.*;
import com.yd.domain.commom.PageModel;
import com.yd.domain.searchParam.OrderParam;
import com.yd.domain.sys.DicEnum;
import com.yd.domain.sys.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by sunxianhui on 2018/5/14.
 */
@Service
public class WebOrderService extends BaseService {
    @Autowired
    private UserCartService userCartService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private PermissionService permissionService;
    @Value("${sms.url}")
    private String sms_url;
    @Value("${sms.ID}")
    private String sms_ID;
    @Value("${sms.account}")
    private String sms_account;
    @Value("${sms.psw}")
    private String sms_psw;
    @Autowired
    private MMessageService messageService;
    @Transactional
    public Order addOrderDetail(OrderDetial orderDetial, String userId, String companyName, String realName) throws BusinessException {
        Order order=new Order();
        order.setUserId(userId);
        List<OrderGoods> goods=orderDetial.getGoods();
        //添加订单商品信息
        for(int i=0;i<goods.size();i++){
            goods.get(i).setOrderId(order.getOrderId());
            goods.get(i).setCreateTime(new Date());
            addOrderGoods(goods.get(i));
        }
        //添加订单信息
        order.setIfCoupon(orderDetial.getIfCoupon());
        order.setDealPrice(orderDetial.getDealPrice());
        order.setTotalPrice(orderDetial.getTotalPrice());
        order.setContent(orderDetial.getContent());
        order.setCreateTime(new Date());
        int count= addOrder(order);
        //添加优惠券使用情况信息
        if(orderDetial.getIfCoupon()){
            OrderCoupon orderCoupon=new OrderCoupon();
            orderCoupon.setCouponId(orderDetial.getCouponId());
            orderCoupon.setOrderId(order.getOrderId());
            Boolean flag=addOrderCoupon(orderCoupon);
            if(flag){
                if(orderDetial.getCouNumber()==0){//优惠券使用完了，
                    orderMapper.deleteOrderCouponUser(userId,orderDetial.getCouponId());
                }else{
                    orderMapper.updateOrderCouponUser(userId,orderDetial.getCouponId(),orderDetial.getCouNumber());
                }
            }

        }
        if(count==1){
            //清除购物车内相应信息
            for( OrderGoods og: goods){
                userCartService.deleteCart(userId,og.getGoodsId(),og.getGoodsWeightId());
            }
            //短信通知相关人员
            List<User> users=permissionService.getUserByPermCode(DicEnum.PERM_CODE.ORDER_MSG_RECEIVE);
            for(User u:users){
                String msgCount= SmsModelUtil.ORDER_SMS_YZM(companyName==null?realName:companyName,orderDetial.getId());
                String str= SmsClientSend.sendSms(sms_url,sms_ID,sms_account,sms_psw,u.getPhone(),msgCount );
                Message message =new Message();
                message.setPublishUser(userId);
                message.setContent(msgCount);
                message.setToken(messageService.getToken(u.getId(),userId));
                message.setPublishTime(new Date());
                message.setReceiveUser(u.getId());
                messageService.addMessage(message);
            }
            return order;
        }else {
            throw new BusinessException(500, "添加订单信息失败");
        }
    }
    /**
     * 添加订单
     * @param order
     */
    public int addOrder(Order order) {
        return orderMapper.addOrder(order);
    }

    /**
     * 添加订单——商品
     * @param orderGoods
     */
    public void addOrderGoods(OrderGoods orderGoods) {
        orderMapper.addOrderGoods(orderGoods);
    }

    /**
     * 添加订单——使用优惠券
     * @param orderCoupon
     */
    public Boolean addOrderCoupon(OrderCoupon orderCoupon) {
        boolean flag=false;
        flag= orderMapper.addOrderCoupon(orderCoupon);
        return flag;
    }

    /**
     * 根据条件分页查询
     * @param orderParam
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public PageModel getOrderList(OrderParam orderParam, int pageIndex, int pageSize) {
        PageModel pm = new PageModel();
        int startRow = getStartRow(pageIndex, pageSize);
        List<Order> orderList = orderMapper.getOrderList(orderParam, startRow, pageSize);
        for(int i=0;i<orderList.size();i++){
            List<OrderGoods> goods=orderMapper.selectGoodsByOrderId(orderList.get(i).getOrderId());
            List<String>typeOneList=new ArrayList<>();//一级Ids
            List<String>typeIdList=new ArrayList<>();//二级ids
            Map<String,List<String>> typeMap=new HashMap<>();
            for(OrderGoods og:goods) {
                if (!typeOneList.contains(og.getTypeOne())) {
                    typeOneList.add(og.getTypeOne());
                }
                if (!typeIdList.contains(og.getType())) {
                    typeIdList.add(og.getType());
                }
            }
            orderList.get(i).setgTypeOneIdlist(typeOneList);
            orderList.get(i).setgTypeIdlist(typeIdList);
            orderList.get(i).setGoods(goods);
        }
        int count = 0;
        if (pageIndex == 1) {
            //查询总条数
            count = orderMapper.getOrderCount(orderParam);
            pm.setCount(count);
        }
        pm.setList(orderList);
        return pm;
    }

    /**
     * 删除
     * @param id
     */
    public void deleteOrderByid(String id,String role) throws BusinessException {
        Order o=orderMapper.getOrderById(id);
        if(o!=null&&(o.getPayStatus().equals(DicEnum.PAY_STATUS.PAY) &&o.getStatus().equals(DicEnum.ORDER_STATUS.DEAL))){
            orderMapper.hideOrderByIdForUser(id);//交易完成逻辑删除
        }else if(o!=null&&(o.getPayStatus().equals(DicEnum.PAY_STATUS.UN_PAY) &&o.getStatus().equals(DicEnum.ORDER_STATUS.UN_DEAL))){
            orderMapper.deleteOrderById(id);//交易尚未开始物理删除
        }else{
            throw new BusinessException(401,"交易正在进行,无法删除");
        }

    }

    /**
     * 根据orderId查询
     * @param id
     * @return
     */
    public Order selectOrderById(String id) {
        Order order = orderMapper.selectOrderById(id);
        order.setGoods(orderMapper.selectGoodsByOrderId(id));
        return order;
    }
}
